import {
  Component,
  OnInit,
  Input,
  Output,
  EventEmitter,
  OnChanges,
  OnDestroy
} from "@angular/core";
import { OneMapService } from "../one-map.service";
import { MapUiService } from '../map-ui.service';
const coefficientArr = [
  0.5,
  0.53,
  0.5,
  0.51,
  0.54,
  0.5,
  0.51,
  0.55,
  0.53,
  0.53,
  0.5,
  0.5,
  0.53
];

@Component({
  selector: "app-map-panel",
  templateUrl: "./map-panel.component.html",
  styleUrls: ["./map-panel.component.scss"]
})
export class MapPanelComponent implements OnInit, OnChanges, OnDestroy {
  @Input() panelData: any;
  @Output() kpiChange = new EventEmitter();
  @Output() buildingSelect = new EventEmitter();

  statType: string;
  tabActive: number = 1;

  modalShow: boolean = false;

  pageNum: number = 1;
  pageSize: number = 10;
  total: number;
  panelList: any[] = [];

  statOpt: any = {};
  irrAreaType: any = {
    1: "自流灌区",
    2: "扬水灌区"
  };
  qskArr: string[] = ['db', 'dx', 'gy', 'ny', 'sh', 'gyjc', 'nyjc', 'shjc', 'hhjc'];
  qskArr1: string[] = ['zlqsk', 'qdlqsk', 'bzlqsk', 'sjlqsk', 'blqsk', 'sdzlqsk', 'qtlqsk'];
  dmArr: string[] = ['hh', 'gqdm', 'shg', 'psg', 'hd', 'yz', 'skswz', 'ylz', 'cyylz', 'sqz', 'zygq', 'zypsg'];
  dmArr1: string[] = ['hh', 'gqdm', 'shg', 'psg', 'hd', 'yz', 'skswz', 'zygq', 'zypsg'];
  weatherMap: any = {
    5: '雪',
    6: '雨夹雪',
    7: '雨',
    8: '阴',
    9: '晴'
  };

  flowList: any[] = [
    {
      icon: "icon-intake",
      text: "引水流量",
      value: 0,
      unit: "m³/s"
    },
    {
      icon: "icon-drainage",
      text: "排水流量",
      value: 0,
      unit: "m³/s"
    }
  ];
  totalList: any[] = [
    {
      text: "引水量",
      value: 0,
      unit: "万m³"
    },
    {
      text: "排水量",
      value: 0,
      unit: "万m³"
    },
    {
      text: "耗水量",
      value: 0,
      unit: "万m³"
    }
  ];
  alertList: any[] = [];
  monitorList: any[] = [];
  warningList: any[] = [];
  selectedList: any[] = [];
  interval: any;

  constructor(private mapService: OneMapService, private mapUiService: MapUiService) { }

  ngOnInit(): void {
    this.mapUiService.selectChange.subscribe(list => {
      if (list.length < 9) {
        this.selectedList = [list];
      } else if (list.length < 17) {
        this.selectedList[0] = list.slice(0, 8);
        this.selectedList[1] = list.slice(8, 16);
      } else if (list.length < 25) {
        this.selectedList[0] = list.slice(0, 8);
        this.selectedList[1] = list.slice(8, 16);
        this.selectedList[2] = list.slice(16, 24);
      } else {
        this.selectedList[0] = list.slice(0, 8);
        this.selectedList[1] = list.slice(8, 16);
        this.selectedList[2] = list.slice(16, 24);
        this.selectedList[3] = list.slice(24, 32);
      }
    });
  }

  ngOnChanges(): void {
    this.initData();
  }

  ngOnDestroy(): void {
    clearInterval(this.interval);
    this.interval = null;
  }

  initData() {
    this.pageNum = 1;
    if (this.interval) {
      clearInterval(this.interval);
      this.interval = null;
    }
    if (this.panelData.mode == "base") {
      this.getPanalList();
    } else if (this.panelData.mode == 'monitor' || this.panelData.mode == 'irrProject') {
      this.getMonitorList();
    } else if (this.panelData.mode == 'major') {
      // this.getMonitorData();
      this.pageSize = 20;
      this.getMonitorList();
      this.interval = setInterval(() => {
        const data = this.panelData;
        this.statType = data.layerName.split("_").pop();
        const params = {
          stationId: data.stationId || "",
          sectionId: data.sectionId || ""
        };
        this.mapService
          .queryMonitorList({
            type: this.statType,
            params: {
              ...params,
              pageNum: this.pageNum,
              pageSize: this.pageSize
            }
          })
          .subscribe(res => {
            this.total = res["total"];
            const oldList = this.panelList;
            res['list'].map((item, i) => {
              const oldData = oldList[i];
              oldData.change = false;
              let change = false;
              switch (this.statType) {
                case 'cyylz':
                  change = item.dyp != oldData.dyp;
                  break;
                case 'gyjc':
                case 'nyjc':
                case 'shjc':
                case 'hhjc':
                  change = item.mpQ != oldData.mpQ;
                  break;
                case 'hh':
                  change = item.waterHeight != oldData.waterHeight || item.flux != oldData.flux || item.heightInside != oldData.heightInside || item.fluxIncome != oldData.fluxIncome;
                  break;
                case 'zygq':
                case 'zypsg':
                  change = item.waterHeight != oldData.waterHeight || item.flux != oldData.flux;
                  break;
                case 'zyzm':
                  change = item.degreeMax != oldData.degreeMax || item.validStrobe != oldData.validStrobe;
                  break;
                case 'zybz':
                  change = item.instanFlow != oldData.instanFlow;
                  break;
              }
              if (change) {
                oldList[i] = {
                  ...item,
                  change: true
                };
                this.panelList = [...oldList];
              }
            });
          });
      }, 30 * 1000);
    }
  }

  getPanalList() {
    const data = this.panelData;
    if (!data.layerName || typeof(data.layerName) == 'object') {
      return;
    }
    if (data.layerName == "view_zuzhi@1") {
      data.layerName = "office";
    } else if (data.layerName == "view_zuzhi@2") {
      data.layerName = "station";
    }
    this.statType = data.layerName.split("_").pop();
    const params = {};
    if (data.layerName == "office") {
      params["id"] = data.stationId || "";
    } else if (data.layerName == "station") {
      if (data.sectionId) {
        params["id"] = data.sectionId;
      } else {
        params["pid"] = data.stationId || "";
      }
    } else {
      params["stationId"] = data.stationId || "";
      params["sectionId"] = data.sectionId || "";
    }

    if (this.statType == "bengzhan") {
      params["pumpType"] = "01";
    } else if (this.statType == "bengzhan2") {
      params["pumpType"] = "11";
      this.statType = "bengzhan";
    } else if (this.statType == "guanyu") {
      this.statType = "irrArea";
    }
    // if (!data.checked) {
    //   this.statType = "irrArea";
    //   params["stationId"] = data.stationId || "";
    //   params["sectionId"] = data.sectionId || "";
    // }
    console.log('statType: ' + this.statType);
    this.mapService
      .queryBaseList({
        type: this.statType,
        params: {
          ...params,
          pageNum: this.pageNum,
          pageSize: this.pageSize
        }
      })
      .subscribe(res => {
        // console.log(res);
        this.total = res["total"];
        this.panelList = res["list"];
      });
    this.mapService
      .queryBaseList({
        type: this.statType,
        params: {
          ...params,
          pageSize: 20000
        }
      })
      .subscribe(res => {
        const baseList = res["list"];
        if (this.statType == "irrArea") {
          baseList.forEach((item, index) => {
            item["irrCoefficient"] = coefficientArr[index];
          });
        }
        this.statOpt = {
          statType: this.statType,
          baseList
        };
      });
  }

  getMonitorList() {
    const data = this.panelData;
    this.statType = data.layerName.split("_").pop();
    const params = {
      stationId: data.stationId || "",
      sectionId: data.sectionId || ""
    };
    switch (this.statType) {
      case "bengzhan":
        params["pumpType"] = "01";
        break;
    }
    this.mapService
      .queryMonitorList({
        type: this.statType,
        params: {
          ...params,
          pageNum: this.pageNum,
          pageSize: this.pageSize
        }
      })
      .subscribe(res => {
        this.total = res["total"];
        this.panelList = res["list"].map(item => {
          if (item.info && typeof item.info == "object") {
            item = {
              ...item,
              ...item.info
            };
          }
          return item;
        });
      });
  }

  getItemValues(list, key) {
    return list.map(i => {
      return i[key] || 0;
    });
  }

  onSelectBuilding(item) {
    console.log(item);
    this.buildingSelect.emit({
      ...item,
      layer: this.statType
    });
  }

  getMonitorData() {
    this.mapService.getStatisMuw().subscribe(res => {
      this.flowList[0].value = res["mwoFlow"];
      this.flowList[1].value = res["dwoFlow"];
      this.totalList[0].value = res["mwoTotal"];
      this.totalList[1].value = res["dwoTotal"];
      this.totalList[2].value = res["cwoTotal"];
    });
    this.mapService.getStaticData({}).subscribe((list: Array<any>) => {
      this.alertList = list.filter(item => {
        return Number(item.id) <= 12 && item.totalUse > item.planUseTotal;
      });
    });
    this.mapService.getStatisList({}).subscribe((list: Array<any>) => {
      this.monitorList = list;
    });
    this.mapService.getWarningList().subscribe(res => {
      this.warningList = res.list;
    });
  }

  onClickIcon(node) {
    this.panelData = {
      ...this.panelData,
      layerName: node.layerName,
      checked: true
    };
    this.initData();
  }

  onSwitch(node) {
    node.labelOff = !node.labelOff;
    this.mapUiService.labelOffChange.next(node);
  }
}
